#include "app_message.h"
#include "app_common.h"
#include <stdio.h>
#include <string.h>

/**
 * @brief 字符数组转json格式
 */

 char *app_message_str2json(char *data,int data_len){
    char *id_str = app_common_str2hex(data+3,data[1]);
    char *msg_str = app_common_str2hex(data+3+data[1],data[2]);
    cJSON *hex = cJSON_CreateObject();
    cJSON_AddNumberToObject(hex,"conn_type",data[0]);
    cJSON_AddStringToObject(hex,"id",id_str);
    cJSON_AddStringToObject(hex,"msg", msg_str);
    char *hexstr = cJSON_PrintUnformatted(hex);
    return hexstr;
 }

 /**
  * @brief json格式转字符数组
  */
 int app_message_json2str(char *json_str,char *data,int len){
    cJSON *root = cJSON_Parse(json_str);
    cJSON *conn_type_json = cJSON_GetObjectItem(root,"conn_type");
    cJSON *id_json = cJSON_GetObjectItem(root,"id");
    cJSON *msg_json = cJSON_GetObjectItem(root,"msg");

    char conn_type = conn_type_json->valueint;
    char *id_hex = id_json->valuestring;
    char *msg_hex = msg_json->valuestring;

    char id[strlen(id_hex)/2];
    char msg[strlen(msg_hex)/2];
    
    int id_len = app_common_hex2str(id_hex,id,strlen(id_hex)/2);
    int msg_len = app_common_hex2str(msg_hex,msg,strlen(msg_hex)/2);

    data[0] = conn_type;
    data[1] = id_len;
    data[2] = msg_len;
    memcpy(data+3,id,id_len);
    memcpy(data+3+id_len,msg,msg_len);

    int data_len = 3 + id_len + msg_len;
    return data_len;
 }
